<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/context/mytags.jsp"%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>选择机床-预约实验室</title>
<t:base type="jquery,easyui,tools,DatePicker"></t:base>
<meta name="keywords" content="jQuery,选座">
<link rel="stylesheet" type="text/css" href="webpage/com/mengtian_tech/smart_lab/room/selectSeats.css?v=3" />
<style type="text/css">

</style>

</head>

<body>
<input id="computerRoomId" name='computerRoomId' type="hidden" value="${computerRoom.id }"/>
<input id="deviceId"  type="hidden" />
<input id="deviceApplyId"  type="hidden" value="${deviceApplyId }"/>

<div id="historyInfo"></div>
<div id="main">
   <div class="demo">
   		<div id="seat-map">
   			<div id="legend"></div>
			<div class="front">讲台</div>					
		</div>
		<div class="booking-details">
			<p>开始时间：<span>
				<input name="applyDate"></span>
			</p>
			<p>结束时间：<span>
				<input name="applyEndDate"></span>
			</p>
			<p>座位：</p>
			<ul id="selected-seats"></ul>
			 
			<button class="checkout-button" style="height: 30px">提交预约</button>
				
			<div id='appointInfo' style='color:red;'>
				
			</div>
		</div>
		<div style="clear:both"></div>
   </div>
	
  <br/>
</div>
<script type="text/javascript" src="plug-in/jquery/jquery.min1.7.js"></script>
<script src = "webpage/com/mengtian_tech/smart_lab/room/jquery.seat-charts.min.js"></script>
<script type="text/javascript">

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var selectedSeats = '${selectedSeats}';
if(!(selectedSeats=="hasSeleted")){
	selectedSeats = selectedSeats.split(",");
}

var deviceList = [];
<c:forEach items="${labDeviceList}" var="device">
	deviceList.push({name:'${device.machineName}',id:'${device.id}'});
</c:forEach>
 
var seatMap = [];
var colCount = 0;
var colStr = "";
for(var i=0;i<deviceList.length;i++){
	colStr +="a";
	colCount ++;
	
	if(colCount >= 5){
		seatMap.push(colStr);
		colStr='';
		colCount = 0;
	}
}
if(colStr !='')seatMap.push(colStr);

$(document).ready(function() {
	var maxSeatsSelect = 1;//最大可选座位数
	var selectedCount = 0;//已选座位
	
	var $cart = $('#selected-seats') //座位区
	
	var sc = $('#seat-map').seatCharts({
		map: seatMap,
		naming : {
			top : false,
			getLabel : function (character, row, column) {
				var index = (row-1)*5+column;
				var obj = deviceList[index-1];
				return obj.name;
			},
			getId  : function(character, row, column) {
				var index = (row-1)*5+column;
				var obj = deviceList[index-1];
				return obj.id;
			}
		},
		legend : { //定义图例
			node : $('#legend'),
			items : [
				[ 'a', 'available',   '可选' ],
				[ 'a', 'unavailable', '已预约']
			]					
		},
		
		click: function () { //点击事件
			if (this.status() == 'available'&&selectedCount<maxSeatsSelect) { //可选座
				$('<li>'+(this.settings.label)+"</li>")
					.attr('id', 'cart-item-'+this.settings.id)
					.data('seatId', this.settings.id)
					.appendTo($cart);
			
				selectedCount++;
		 		var id = this.settings.id;
		 		var label = this.settings.label;
		 		var getURL = "computerRoomController.do?getAppointList&deviceId="+id;
				$.ajax({
					url:getURL,
					success:function(data){
						data = $.parseJSON(data);
						if(data.length > 0){
							$('#appointInfo').append(label+"已被预约信息：<br>");
							for(var i=0;i<data.length;i++){
								var start = data[i].start;
								var end = data[i].end;
								$('#appointInfo').append(start+"至"+end+"<br>");
							}
						}else{
							$('#appointInfo').html('');
						}
					}		
				});
				
				return 'selected';
			} else if (this.status() == 'selected') { //已选中
					//删除已预订座位
					$('#cart-item-'+this.settings.id).remove();
					$('#appointInfo').html('');
					selectedCount--;
					//可选座
					return 'available';
			} else if (this.status() == 'unavailable') { //已售出
				return 'unavailable';
			} else {
				return this.style();
			}
		}
	});
	
	//已售出的座位
	initUnavailableSeats(sc);
	
	$("input[name='applyDate']").attr("class","Wdate").click(function(){
		WdatePicker({minDate:'${nowDate}',maxDate:'${maxDate}', dateFmt:'yyyy-MM-dd HH:mm'});});
	$("input[name='applyEndDate']").attr("class","Wdate").click(function(){
		WdatePicker({minDate:'${nowDate}',maxDate:'${maxDate}',dateFmt:'yyyy-MM-dd HH:mm'});});
	
	$(".checkout-button").click(function(){
		var selectedSeats = null;
		sc.find('selected').each(function () {
			var row = this.settings.row;
			var column = this.settings.column;
			
			var index = (row)*5+column;
			selectedSeats = deviceList[index];
		});
		
		if(!validate()){
			return;
		}
		
		if(selectedSeats!=null){
			$.ajax({
				url : 'computerRoomController.do?saveDeviceApply',
				type : 'post', 
				cache : false,
				data: {"selectedSeats":selectedSeats.id, "applyDate": $("input[name='applyDate']").val(),"applyEndDate": $("input[name='applyEndDate']").val() , "computerRoomId":$('#computerRoomId').val(), "deviceApplyId":$('#deviceApplyId').val() },
				success : function(data) {
					var d = $.parseJSON(data);
					if (d.success) {
						var msg = d.msg;
						tip(msg);
						frameElement.api.close();   
					}else{
						tip(d.msg);
					}
				}
			});
		}else{
			tip("请选择设备");
			return;
		}
	});
	showSeatHistoryInfo();
});
 

function validate(){
 
	
	if($("input[name='applyDate']").val()==""){
		tip("请选择开始时间");
		return false;
	}
	if($("input[name='applyEndDate']").val()==""){
		tip("请选择结束时间");
		return false;
	}
	if($("input[name='applyDate']").val()<new Date().Format("yyyy-MM-dd HH:mm:ss")){
		tip("开始时间不能早于当前时间");
		return false;
	}
	if($("input[name='applyEndDate']").val()<=new Date().Format("yyyy-MM-dd HH:mm:ss")){
		tip("结束时间不能早于当前时间");
		return false;
	}
	if($("input[name='applyDate']").val()>=$("input[name='applyEndDate']").val()){
		tip("开始时间不能晚于结束时间");
		return false;
	}
	return true;
}

//已售出的座位
function initUnavailableSeats(sc){
	var unavailableSeats = [];
	if(selectedSeats=="hasSeleted"){
		for(var i=0;i<deviceList.length;i++){ 
			unavailableSeats.push(deviceList[i].id); 
		}
	}else{
		for(var i=0; i<selectedSeats.length;i++){
			unavailableSeats.push(selectedSeats[i]);
		}
	}
	sc.get(unavailableSeats).status('unavailable');
}

function showSeatHistoryInfo(){
	var historySeat = "${historySeat}";
	if(!(historySeat=="")){
		var html = "预约未通过，预约的座位为："+ historySeat+"， 预约时间为：${beginDate} 至  ${endDate}";
	}else{
		$("#historyInfo").hide();
	}
	$("#historyInfo").append(html);
}

</script>
</body>
</html>